﻿namespace Als.Utils.Pay.UnionPay
{
    using System;
    using System.Globalization;
    using System.IO;
    using System.Numerics;
    using System.Security.Cryptography;
    using System.Security.Cryptography.X509Certificates;

    public class CertUtil
    {
        public static string GetSignCertId(string signCertpath, string signCertpwd)
        {
            X509Certificate2 certificate = new X509Certificate2(signCertpath, signCertpwd, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);
            return BigInteger.Parse(certificate.SerialNumber, NumberStyles.HexNumber).ToString();
        }

        public static RSACryptoServiceProvider GetSignProviderFromPfx(string signCertpath, string signCertpwd)
        {
            X509Certificate2 certificate = new X509Certificate2(signCertpath, signCertpwd, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);
            return (RSACryptoServiceProvider) certificate.PrivateKey;
        }

        public static RSACryptoServiceProvider GetValidateProviderFromPath(string certId, string validateCertdir)
        {
            FileInfo[] files = new DirectoryInfo(validateCertdir).GetFiles("*.cer");
            if ((files != null) && (0 != files.Length))
            {
                foreach (FileInfo info2 in files)
                {
                    X509Certificate2 certificate = new X509Certificate2(info2.DirectoryName + @"\" + info2.Name);
                    string str = BigInteger.Parse(certificate.SerialNumber, NumberStyles.HexNumber).ToString();
                    if (certId.Equals(str))
                    {
                        return (RSACryptoServiceProvider) certificate.PublicKey.Key;
                    }
                }
            }
            return null;
        }
    }
}

